package com.jingdong.controller;


import com.jingdong.enity.User;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/m1")
    public String m1() {
        return "啊哈没想到吧";
    }

    @RequestMapping("/register")
    public String register(User user) throws Exception {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //获取连接
        String connection = "jdbc:mysql://localhost:3306/taobao";
        String dbUsername = "root";
        String dbPassword = "123456";
        Connection conn = DriverManager.getConnection(connection, dbUsername, dbPassword);
        //准备sql语句
        String sql = "insert into user(name,password,birthday) values(?,?,?)";
        //获取传输器对象
        PreparedStatement pstm = conn.prepareStatement(sql);
        //给问号赋值
        pstm.setString(1, user.getUsername());
        pstm.setString(2, user.getPassword());
        pstm.setString(3, user.getBirthday().toString());
        //执行SQL
        int count = pstm.executeUpdate();
        return count > 0 ? "注册成功" : "注册失败";
    }
    //下面的是查询
    @Test
    public void testQuery1() throws Exception {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/taobao";
        String dbUsername = "root";
        String dbPassword = "123456";
        //获取连接
        Connection connection = DriverManager.getConnection(url, dbUsername, dbPassword);
        //准备需要执行的SQL语句
        String sql = "select * from user where name = ?";
        //获取传输器对象
        PreparedStatement pstm = connection.prepareStatement(sql);
        //给问号赋值
        pstm.setString(1, "zs");
        //执行SQL,获取结果集
        ResultSet resultSet = pstm.executeQuery();
        //处理结果集
        if(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String password = resultSet.getString("password");
            String birthday = resultSet.getString("birthday");

            System.out.println(id);
            System.out.println(name);
            System.out.println(password);
            System.out.println(birthday);
        }
    }
}
